import axios from "@/util/http";
import store from "@/store/index";
import { ElNotification } from "element-plus";
// import { useStore } from "vuex";

export default {
  state: {
    jwt_token: "",
    username: "",
    id: "",
    id_kind: -1,
    id_kind_string: "",
    is_login: false,
    is_pulling_info: false,

    socketUrl: "",
    socket: null,
  },
  getters: {},
  mutations: {
    setJwtToken(state, token) {
      state.jwt_token = token;
    },
    logout(state) {
      state.is_login = false;
      state.jwt_token = "";
      state.id = "";
      state.id_kind = -1;
      state.id_kind_string = "";
      state.is_pulling_info = false;
      localStorage.removeItem("jwt_token");
    },
    getPostConfig(state) {
      return {
        headers: {
          Authorization: "Bearer " + state.jwt_token,
        },
      };
    },
    setIdKindStr(state, idKind) {
      if (idKind == 0) {
        state.id_kind_string = "顾客";
      } else if (idKind == 1) {
        state.id_kind_string = "服务员";
      } else if (idKind == 2) {
        state.id_kind_string = "厨师";
      } else if (idKind == 3) {
        state.id_kind_string = "管理员";
      } else {
        state.id_kind_string = "未知";
      }
    },
    setIsLogin(state, flag) {
      state.is_login = flag;
      store.state.is_login = flag;
      // useStore().is_login = flag;
    },
    getIsLogin(state) {
      return state.is_login;
    },
  },
  actions: {
    get_current_user_info(context, data) {
      context.state.is_pulling_info = true;
      const config = {
        headers: {
          Authorization: "Bearer " + context.state.jwt_token,
        },
      };
      axios
        .post("/user/get/current/user/info/", data, config)
        .then((resp) => {
          if (resp.data.code == 200) {
            const user = context.state;
            const info = resp.data.data;
            user.username = info.username;
            user.id = info.id;
            user.id_kind = info.idKind;
            if (user.id_kind == "1" || user.id_kind == "2") {
              context.dispatch("connect_websocket");
            }
            context.commit("setIsLogin", true);
            context.commit("setIdKindStr", info.idKind);
            context.state.is_pulling_info = false;
            data.success(resp.data);
          } else {
            context.state.is_pulling_info = false;
            data.error(resp.data);
          }
        })
        .catch((error) => {
          data.error(error);
        });
    },
    connect_websocket(context) {
      // webSocket 测试
      context.state.socketUrl =
        `ws://127.0.0.1:3000/websocket/` + context.state.id + `/`;
      context.state.socket = null;

      context.state.socket = new WebSocket(context.state.socketUrl); //js自带的WebSocket()

      context.state.socket.onopen = () => {
        //连接成功时调用的函数
        console.log("connected!");
      };

      context.state.socket.onmessage = (msg) => {
        //前端接收到信息时调用的函数
        const data = JSON.parse(msg.data);
        if (data.code == 200) {
          if (data.message == "111") {
            store.dispatch("get_all_unpaid_orders", {
              token: store.state.jwt_token,
            });
            ElNotification({
              title: "请注意",
              message: "有新的订单，请注意查收",
              duration: 0,
              type: "warning",
            });
          } else if (data.message == "222") {
            store.dispatch("get_all_unfinished_order_item", {
              token: store.state.jwt_token,
            });
            ElNotification({
              title: "请注意",
              message: "有新的菜品待做，请注意查收",
              duration: 0,
              type: "warning",
            });
          }
        }
      };

      context.state.socket.onclose = () => {
        //关闭时调用的函数
        console.log("disconnected!");
      };
    },
    disconnect_websocket(context) {
      if (context.state.id_kind == 1 || context.state.id_kind == 2) {
        context.state.socket.close();
      }
    },
  },
  modules: {},
};
